<?php

namespace Robot\Controller;

class ProductController extends AdminbaseController {

    function _initialize() {
        parent::_initialize();
        $this->currentModel = D("Product");
    }

    //首页
    public function index() {

        $map["r.status"] = C("ROUND_STATUS.WAITING");

        $list = D("Round")->alias("r")
            ->join("left join __PRODUCT__ p on p.product_id = r.product_id")
            ->join("left join __ORDER__ o on o.order_id = r.winner_order")
            ->join("left join __GROUP__ g on g.group_id = o.group_id")
            ->join("left join __CUSTOMER__ c on c.customer_id = r.winner_customer_id")
            ->join("left join __CUSTOMER__ gc on gc.customer_id = g.customer_id")
            ->where($map)
            ->field("p.*,r.round_id,c.nickname,gc.nickname as group_nickname,
                r.join_number,r.group_number,r.progress")
            ->select();

        $this->assign('list', $list);
        $this->display();

    }

    public function robotList() {

        $roundId = I("post.id");

        $groupMemberMap["g.round_id"] = $roundId;
        $groupMemberMap["g.status"] = array("neq", C("GROUP_STATUS.SYSTEM_ABANDON"));

        if(!isNullOrEmpty($roundId)) {
            $groupMemberList = D("GroupMember")->alias("gm")
                ->join("left join __GROUP__ g on g.group_id = gm.group_id")
                ->where($groupMemberMap)
                ->field("gm.customer_id")
                ->select();
            if(!isNullOrEmpty($groupMemberList)) {
                $map["customer_id"] = array("not in", array_column($groupMemberList, "customer_id"));
            }
        }

        $map["is_robot"] = C("DEFAULT_YN.YES");

        $robotList = D("customer")
            ->where($map)
            ->field("nickname as text,customer_id as id")
            ->select();

        $data["results"] = $robotList;

        header('Content-Type: '.'json'.'; charset='.'utf-8');

        echo json_encode($data);
    }

    public function createGroup() {

        $roundId = $_REQUEST["id"];

        $this->assign('id', $roundId);
        $this->display('createGroup');

    }

    public function randAdd() {

        $groupId = $_REQUEST["id"];
        $number = $_REQUEST["number"];

        if($number <= 0) {
            $this->error("对不起，请输入正确的数字");
            exit();
        }

        $group = D("Group")->queryById($groupId);
        $round = D("Round")->queryById($group["round_id"]);
        $product = D("Product")->queryById($round["product_id"]);

        $leftNumber = $product["price"] - $round["join_number"];

        if($leftNumber < $number) {
            $this->error("对不起，剩余余额份数不足");
            exit();
        }

        $groupMemberMap["g.round_id"] = $group["round_id"];
        $groupMemberMap["g.status"] = array("neq", C("GROUP_STATUS.SYSTEM_ABANDON"));

        $groupMemberList = D("GroupMember")->alias("gm")
            ->join("left join __GROUP__ g on g.group_id = gm.group_id")
            ->where($groupMemberMap)
            ->field("gm.customer_id")
            ->select();
        if(!isNullOrEmpty($groupMemberList)) {
            $map["customer_id"] = array("not in", array_column($groupMemberList, "customer_id"));
        }

        $map["is_robot"] = C("DEFAULT_YN.YES");

        $robotList = D("customer")
            ->where($map)
            ->order("rand()")
            ->field("customer_id")
            ->limit($number)
            ->select();

        $count = count($robotList);

        if($count != $number) {
            $this->error("对不起，机器人数量不足");
            exit();
        }

        //round回写数字
        $round["join_number"] = $round["join_number"] + $number;
        $round["progress"] = sprintf("%.2f",$round["join_number"]/$product["price"]*100);

        D("Round")->updateInfo($round);

        //数据回写
        $group["buy_number"] = $group["buy_number"] + $number;
        $group["member_number"] = $group["member_number"] + $number;
        D("Group")->updateInfo($group);

        foreach ($robotList as $robot) {

            //添加团员
            $groupMemberData["group_id"] = $groupId;
            $groupMemberData["customer_id"] = $robot["customer_id"];
            $groupMemberData["create_time"] = getCurrentDate();
            $groupMemberData["number"] = 1;
            $groupMemberData["update_time"] = getCurrentDate();

            D("GroupMember")->add($groupMemberData);

            //添加订单
            $orderData["round_id"] = $group["round_id"];
            $orderData["customer_id"] = $robot["customer_id"];
            $orderData["create_time"] = getCurrentDate();
            $orderData["number"] = 1;
            $orderData["group_id"] = $groupId;
            $orderData["status"] = C("ORDER_STATUS.WAITING_OPEN");
            $orderData["pay_id"] = 0;

            $orderId = D("Order")->add($orderData);

            //todo
            $genOrderData['orderId'] = $orderId;
            curlPost('http://114.215.113.76:9502/genOrderRecord',$genOrderData);

            $pushData['orderId'] = $orderId;
            curlPost('http://114.215.113.76:9502/pushNotification',$pushData);

        }

        $this->success("添加成功", U("product/detail", array("id"=>$group["round_id"])));

    }

    public function createGroupPost() {

        $roundId = $_REQUEST["roundId"];
        $customerId = $_REQUEST["customerId"];
        $number = $_REQUEST["number"];

        $groupMemberMap["gm.customer_id"] = $customerId;
        $groupMemberMap["g.round_id"] = $roundId;
        $groupMemberMap["g.status"] = array("neq", C("GROUP_STATUS.SYSTEM_ABANDON"));

        $groupMember = D("GroupMember")->alias("gm")
            ->join("left join __GROUP__ g on g.group_id = gm.group_id")
            ->where($groupMemberMap)->find();

        if(!isNullOrEmpty($groupMember)) {
            $this->error("对不起，该成员已经参与过该轮购买，不能创建团");
            exit();
        }

        $round = D("Round")->queryById($roundId);
        $product = D("Product")->queryById($round["product_id"]);

        $leftNumber = $product["price"] - $round["join_number"];

        if($leftNumber < $number) {
            $this->error("对不起，剩余余额份数不足");
            exit();
        }

        //round回写数字
        $round["join_number"] = $round["join_number"] + $number;
        $round["group_number"] = $round["group_number"] + 1;
        $round["progress"] = sprintf("%.2f",$round["join_number"]/$product["price"]*100);

        D("Round")->updateInfo($round);

        //创建团
        $groupData["round_id"] = $roundId;
        $groupData["create_time"] = getCurrentDate();
        $groupData["customer_id"] = $customerId;
        $groupData["status"] = C("GROUP_STATUS.WAITING_JOIN");
        $groupData["member_number"] = 1;
        $groupData["buy_number"] = $number;

        $groupId = D("Group")->add($groupData);

        //添加团员
        $groupMemberData["group_id"] = $groupId;
        $groupMemberData["customer_id"] = $customerId;
        $groupMemberData["create_time"] = getCurrentDate();
        $groupMemberData["number"] = $number;
        $groupMemberData["update_time"] = getCurrentDate();

        D("GroupMember")->add($groupMemberData);

        //添加订单
        $orderData["round_id"] = $roundId;
        $orderData["customer_id"] = $customerId;
        $orderData["create_time"] = getCurrentDate();
        $orderData["number"] = $number;
        $orderData["group_id"] = $groupId;
        $orderData["status"] = C("ORDER_STATUS.WAITING_OPEN");
        $orderData["pay_id"] = 0;

        $orderId = D("Order")->add($orderData);

        //todo
        $genOrderData['orderId'] = $orderId;
        curlPost('http://114.215.113.76:9502/genOrderRecord',$genOrderData);

        $pushData['orderId'] = $orderId;
        curlPost('http://114.215.113.76:9502/pushNotification',$pushData);

        $this->success("创建团成功", U("product/createGroup", array("id"=>$roundId)));

    }

    public function rank() {

        $roundId = $_REQUEST["id"];
        $nickname = $_REQUEST["nickname"];

        if(!isNullOrEmpty($nickname)) {
            $map["c.nickname"] = array("like", "%$nickname%");
            $this->assign("nickname", $nickname);
        }

        $map["g.round_id"] = $roundId;
        $map["g.status"] = array("neq", C("GROUP_STATUS.WAITING_PAY"));

        $list = D("GroupMember")->alias("gm")
            ->join("left join __GROUP__ g on g.group_id = gm.group_id")
            ->join("left join __CUSTOMER__ c on c.customer_id = gm.customer_id")
            ->join("left join __CUSTOMER__ gc on gc.customer_id = g.customer_id")
            ->where($map)
            ->field("gm.*,c.nickname,c.headimgurl,c.openid,gc.nickname as group_nickname")
            ->order("gm.number desc")
            ->select();

        $this->assign("roundId", $roundId);
        $this->assign('list', $list);
        $this->display();

    }

    public function detail() {

        $roundId = $_REQUEST["id"];
        $nickname = $_REQUEST["nickname"];

        if(!isNullOrEmpty($nickname)) {
            $map["c.nickname"] = array("like", "%$nickname%");
            $this->assign("nickname", $nickname);
        }

        $map["g.round_id"] = $roundId;
        $map["g.status"] = array("eq", C("GROUP_STATUS.WAITING_JOIN"));

        $list = D("Group")->alias("g")
            ->join("left join __CUSTOMER__ c on c.customer_id = g.customer_id")
            ->order("g.buy_number desc")
            ->field("g.*,c.headimgurl,c.nickname")
            ->where($map)
            ->select();

        $this->assign('roundId', $roundId);
        $this->assign('list', $list);
        $this->display();

    }

    public function addMember() {

        $groupId = $_REQUEST["id"];

        $group = D("Group")->queryById("$groupId");

        $this->assign("roundId", $group["round_id"]);
        $this->assign('id', $groupId);
        $this->display('addMember');

    }

    public function addMemberPost() {

        $groupId = $_REQUEST["groupId"];
        $customerId = $_REQUEST["customerId"];
        $number = $_REQUEST["number"];

        $group = D("Group")->queryById($groupId);

        $groupMemberMap["gm.customer_id"] = $customerId;
        $groupMemberMap["g.round_id"] = $group["round_id"];
        $groupMemberMap["g.group_id"] = array("neq", $groupId);
        $groupMemberMap["g.status"] = array("neq", C("GROUP_STATUS.SYSTEM_ABANDON"));

        $groupMember = D("GroupMember")->alias("gm")
            ->join("left join __GROUP__ g on g.group_id = gm.group_id")
            ->where($groupMemberMap)->find();

        if(!isNullOrEmpty($groupMember)) {
            $this->error("对不起，该成员已经参与过该轮购买，不能创建团");
            exit();
        }

        $round = D("Round")->queryById($group["round_id"]);
        $product = D("Product")->queryById($round["product_id"]);

        $leftNumber = $product["price"] - $round["join_number"];

        if($leftNumber < $number) {
            $this->error("对不起，剩余余额份数不足");
            exit();
        }

        //round回写数字
        $round["join_number"] = $round["join_number"] + $number;
        $round["progress"] = sprintf("%.2f", $round["join_number"]/$product["price"]*100);

        D("Round")->updateInfo($round);

        $groupMember = D("GroupMember")
                ->where(array(
                    "customer_id" => $customerId,
                    "group_id" => $groupId
                ))->find();

        if(isNullOrEmpty($groupMember)) {
            //添加团员
            $groupMemberData["group_id"] = $groupId;
            $groupMemberData["customer_id"] = $customerId;
            $groupMemberData["create_time"] = getCurrentDate();
            $groupMemberData["number"] = $number;
            $groupMemberData["update_time"] = getCurrentDate();

            D("GroupMember")->add($groupMemberData);
            $group["member_number"] = $group["member_number"] + 1;
        } else {
            $groupMember["number"] = $groupMember["number"] + $number;
            D("GroupMember")->updateInfo($groupMember);
        }

        //数据回写
        $group["buy_number"] = $group["buy_number"] + $number;
        D("Group")->updateInfo($group);

        //添加订单
        $orderData["round_id"] = $group["round_id"];
        $orderData["customer_id"] = $customerId;
        $orderData["create_time"] = getCurrentDate();
        $orderData["number"] = $number;
        $orderData["group_id"] = $groupId;
        $orderData["status"] = C("ORDER_STATUS.WAITING_OPEN");
        $orderData["pay_id"] = 0;

        $orderId = D("Order")->add($orderData);

        //todo
        $genOrderData['orderId'] = $orderId;
        curlPost('http://114.215.113.76:9502/genOrderRecord',$genOrderData);

        //广播
        $pushData['orderId'] = $orderId;
        curlPost('http://114.215.113.76:9502/pushNotification',$pushData);

        $this->success("添加成功", U("product/addMember", array("id"=>$groupId)));

    }

    public function win() {

        $memberId = $_REQUEST["id"];
        $groupMember = D("GroupMember")->queryById($memberId);
        $group = D("Group")->queryById($groupMember["group_id"]);
        $round = D("Round")->queryById($group["round_id"]);

        if($round["status"] == C("ROUND_STATUS.END")) {
            $this->error("对不起，此轮游戏已经结束");
            exit();
        }

        if($round["draw_type"] == C("DRAW_TYPE.FIXED")) {
            $this->error("对不起，此轮已经指定过中奖人");
            exit();
        }

        $map["o.customer_id"] = $groupMember["customer_id"];
        $map["o.group_id"] = $groupMember["group_id"];

        $orderRecord = D("OrderRecord")->alias("r")
            ->join("left join __ORDER__ o on o.order_id = r.order_id")
            ->where($map)
            ->order("rand()")
            ->field("r.order_code")
            ->find();

        $order = D("Order")->queryById($orderRecord["order_id"]);

        $round["winner_customer_id"] = $order["customer_id"];
        $round["winner_order"] = $order["order_id"];
        $round["draw_type"] = C("DRAW_TYPE.FIXED");
        $round["win_order_code"] = $orderRecord["order_code"];

        D("Round")->updateInfo($round);

        $this->success("添加成功", U("product/member", array("id"=>$group["group_id"])));

    }

    public function member() {

        $groupId = $_REQUEST["id"];
        $nickname = $_REQUEST["nickname"];

        if(!isNullOrEmpty($nickname)) {
            $map["c.nickname"] = array("like", "%$nickname%");
            $this->assign("nickname", $nickname);
        }

        $map["gm.group_id"] = $groupId;
        $map["g.status"] = array("neq", C("GROUP_STATUS.WAITING_PAY"));

        $list = D("GroupMember")->alias("gm")
            ->join("left join __GROUP__ g on g.group_id = gm.group_id")
            ->join("left join __CUSTOMER__ c on c.customer_id = gm.customer_id")
            ->where($map)
            ->field("gm.*,c.nickname,c.headimgurl,c.openid")
            ->order("gm.number desc")
            ->select();

        $this->assign("groupId", $groupId);
        $this->assign('list', $list);
        $this->display();

    }

}